package com.epam.debrecen.hackathon.com;

import com.epam.debrecen.hackathon.ai.model.GameState;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;

public class InputResolver {
	

	public void resolveServerMessages(String message, GameState gameState ) throws IOException {
		System.out.println("response:" + message.replaceAll("\n", " "));

		BufferedReader reader = new BufferedReader(new StringReader(message));
		String line = null;

		while ((line = reader.readLine()) != null) {

			if (line.equals("Players [")) {
				gameState.setPlayers(this.readBody(reader));
			} else if (line.startsWith("RoundStart")) {
				gameState.startRound();
			} else if (line.equals("Hand [")) {
				gameState.dealCards(this.readBody(reader));
			} else if (line.startsWith("BattleStart")) {
				gameState.startBattle();
			} else if (line.equals("Order [")) {
				gameState.setOrder(this.readBody(reader));
			} else if (line.startsWith("CurrentZone")) {
				gameState.setCurrentZone(line);
			} else if (line.equalsIgnoreCase("GameStart")) {
				gameState.startGame();
			} else if (line.startsWith("GameEnd")) {
				gameState.endGame();
			} else if (line.startsWith("BattleEnd")) {
				gameState.endBattle(getValueOfMessage(line));
			} else if (line.startsWith("Protect")) {
				gameState.protect(getValueOfMessage(line));
			} else if (line.startsWith("RoundEnd")) {
				gameState.endRound();
			} else if (line.startsWith("Player")) {
				gameState.setCurrentPlayer(getValueOfMessage(line));
			} else if(line.startsWith("Play")){
				gameState.playCard(getValueOfMessage(line));
			}
		}

	}

	public String resolveServerRequest(String request, GameState gameState) {

		if ("?Condottiere".equalsIgnoreCase(request)) {
			return gameState.replyAttackedZone();
		}

		if ("?Move".equalsIgnoreCase(request)) {
			return gameState.replySelectedCard();
		}

		if ("?Bishop".equalsIgnoreCase(request)) {
			return gameState.replyProtectedZone();
		}

		if ("?Retrieve".equalsIgnoreCase(request)) {
			return gameState.replyRetrievedCard();
		}

		throw new IllegalStateException("Question is not implemeted. Request:" + request);

	}

	private List<String> readBody(BufferedReader reader) throws IOException {
		List<String> lines = new LinkedList<String>();
		String line = null;
		while ((line = reader.readLine()) != null && !line.equals("]")) {
			lines.add(line);
		}
		return lines;
	}

	private String getValueOfMessage(String input){
		return input.split("")[1];
	}

}
